package me.mayt.df;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 *
 * @author mayt
 * @date 2018/8/30
 */
public class DeleteNullFile {

    public static final Logger LOGGER = LoggerFactory.getLogger(DeleteNullFile.class);

    public static void main(String[] args) {
        if (null == args || args.length == 0) {
            LOGGER.error("param is null");
        }
        deleteNullFile(args);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("path delete end");
        }
    }

    private static void deleteNullFile(String[] args) {
        for (String path : args) {
            deleteNullFile(new File(path));
        }
    }

    private static void deleteNullFile(File file) {
        if (isNullDirectory(file)) {
            boolean isDelete = file.delete();
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("path deleted: {}: {}", isDelete, file.getPath());
            }
            return;
        }
        if (file.isFile()) {
            return;
        }
        File[] subFiles = file.listFiles();
            for (File f : subFiles) {
                deleteNullFile(f);
            }
        if (isNullDirectory(file)) {
            boolean isDelete = file.delete();
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("path deleted: {}: {}", isDelete, file.getPath());
            }
        }
    }

    private static boolean isNullDirectory(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return true;
            }
        }
        return false;
    }
}
